package com.ctvit.sms.platform.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.fop.render.mif.fonts.TimesBold;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.cctv.ldap.LdapDept;
import com.cctv.ldap.LdapPerson;
import com.cctv.ldap.LdapUtils;
import com.ctvit.framework.BusinessException;
import com.ctvit.framework.dao.Condition;
import com.ctvit.framework.dao.OrderPart;
import com.ctvit.framework.security.domain.PermAuthnManager;
import com.ctvit.framework.service.BaseService;
import com.ctvit.sms.platform.domain.ChannSeg;
import com.ctvit.sms.platform.domain.Channel;
import com.ctvit.sms.platform.domain.ComparatorTaskBean;
import com.ctvit.sms.platform.domain.Contentlog;
import com.ctvit.sms.platform.domain.Dept;
import com.ctvit.sms.platform.domain.MsgReg;
import com.ctvit.sms.platform.domain.MsgReq;
import com.ctvit.sms.platform.domain.MsgReqBean;
import com.ctvit.sms.platform.domain.MsgSendlog;
import com.ctvit.sms.platform.domain.MsgSubCat;
import com.ctvit.sms.platform.domain.MsgTask;
import com.ctvit.sms.platform.domain.Person;
import com.ctvit.sms.platform.domain.RecvPerson;
import com.ctvit.sms.platform.domain.RecvSystem;
import com.ctvit.sms.platform.domain.ReqStatRegno;
import com.ctvit.sms.platform.domain.ReqStatSys;
import com.ctvit.sms.platform.domain.SendTaskBean;
import com.ctvit.sms.platform.domain.SubscribeLog;
import com.ctvit.sms.platform.domain.SystemConfig;
import com.ctvit.sms.platform.domain.UnsubList;
import com.ctvit.sms.platform.domain.Unsubscribe;
import com.ctvit.sms.platform.domain.VMsgSubCateInUse;
import com.ctvit.sms.platform.domain.VTask;
import com.ctvit.struts.common.CommonFunc;

import edu.emory.mathcs.backport.java.util.Collections;

public class SmsService extends BaseService {
	private PasswordEncoder passwordEncoder;

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}
	public void insertAllPersons(){
		genericDao.deleteBySqlStr("delete from t_person");
		Person person=null;LdapPerson ldapPerson=null;
		LdapUtils ldapUtils=new LdapUtils();
		List personList=ldapUtils.getAllPersons();
		if (personList==null) personList=new ArrayList();
		List insertPersonList=new ArrayList();
		int ii=0;int jj=0;String dept="";
		
		int a=0;int b=0;
		
		for (int i = 0; i < personList.size(); i++) {
			ldapPerson=(LdapPerson)personList.get(i);
			person=new Person();
			dept=ldapPerson.getOu();
    		//处理部门代码，分离出中心代码，部门代码，科组代码
    		System.out.println("返回的部门代码===="+dept);
    		if(dept!=null&&!dept.equals("")){
    			String[] deptList = dept.split(",");
    			int js = 0;
    			for(int k=0;k<deptList.length;k++){
    				String str = deptList[k];
    				if(str.indexOf("ou=")!=-1){
    					js++;
    				}
    			}
    			//只有中心代码
    			if(js==1){
    	    		a=deptList[0].indexOf("=");
    	    		b=deptList[0].length();
    	    		String zCentre=deptList[0].substring(a+1,b);
    	    		person.setZCentre(zCentre);//中心代码
    			}
    			//有部门和中心代码
    			if(js==2){
    	    		a=deptList[0].indexOf("=");
    	    		b=deptList[0].length();
    	    		String zSector=deptList[0].substring(a+1,b);
    	    		person.setZSector(zSector);//部门代码
    	    		
    	    		a=deptList[1].indexOf("=");
    	    		b=deptList[1].length();
    	    		String zCentre=deptList[1].substring(a+1,b);
    	    		person.setZCentre(zCentre);//中心代码
    			}
    			//有部门和中心代码,科组代码
    			if(js==3){
    	    		a=deptList[0].indexOf("=");
    	    		b=deptList[0].length();
    	    		String zDept=deptList[0].substring(a+1,b);
    	    		person.setZDept(zDept);//科组代码
    				
    	    		a=deptList[1].indexOf("=");
    	    		b=deptList[1].length();
    	    		String zSector=deptList[1].substring(a+1,b);
    	    		person.setZSector(zSector);//部门代码
    	    		
    	    		a=deptList[2].indexOf("=");
    	    		b=deptList[2].length();
    	    		String zCentre=deptList[2].substring(a+1,b);
    	    		person.setZCentre(zCentre);//中心代码
    			}
    		}
    		System.out.println("科组代码==："+person.getZDept());
    		System.out.println("部门代码==："+person.getZSector());
    		System.out.println("中心代码==："+person.getZCentre());
			
			
			
//			ii=dept.indexOf("=");
//    		jj=dept.indexOf(",");
//    		dept=dept.substring(ii+1,jj);
//			person.setZDept(dept);
			
			
			person.setZPerno(ldapPerson.getUid());
    		person.setZPerna(ldapPerson.getCn());
    		person.setZMobph(ldapPerson.getMobile());
    		person.setZCrdat(new Timestamp(Calendar.getInstance().getTimeInMillis()));
    		insertPersonList.add(person);
    		if (insertPersonList.size()%500==0){
    			genericDao.batchInsert(insertPersonList);
    			log.info("本次同步共插入"+insertPersonList.size()+"条人员信息!");
    			insertPersonList=new ArrayList();
    		}
		}
	}
	public void insertAllDepts(){
		genericDao.deleteBySqlStr("delete from t_dept");
		Dept dept=null;LdapDept ldapDept=null;
		LdapUtils ldapUtils=new LdapUtils();
		List deptList=ldapUtils.getAllDept();
		List insertDeptList=new ArrayList();
		if (deptList==null) deptList=new ArrayList();
		for (int i = 0; i < deptList.size(); i++) {
			ldapDept=(LdapDept)deptList.get(i);
			dept=new Dept();
			dept.setZDeptId(ldapDept.getOu());
			dept.setZDeptNm(ldapDept.getDescription());
			dept.setZLevel(ldapDept.getPostalAddress());
			dept.setZOrg(ldapDept.getStreet());
			dept.setZParentId(ldapDept.getPostOfficeBox());
			dept.setZCrdat(new Timestamp(Calendar.getInstance().getTimeInMillis()));
			insertDeptList.add(dept);
			if (insertDeptList.size()%500==0){
    			genericDao.batchInsert(insertDeptList);
    			log.info("本次同步共插入"+insertDeptList.size()+"条部门信息!");
    			insertDeptList=new ArrayList();
    		}
		}
	}
	
	public int removePerson(Person person ) {
		return genericDao.deleteBySqlStr("delete from t_person where z_perno='"+person.getZPerno()+"'");
	}
	public int removeDept(Dept dept ) {
		return genericDao.deleteBySqlStr("delete from t_dept where z_dept_id='"+dept.getZDeptId()+"'");
	}
	public int removeUser(PermAuthnManager permAuthnManager){
		return genericDao.deleteBySqlStr("delete from perm_authn_manager where pk='"+permAuthnManager.getPk()+"' and enabled is null");
	}
	public int insertPerson(Person person){
		genericDao.insert(person);
		return 1;
	}
	public int insertDept(Dept dept){
		genericDao.insert(dept);
		return 1;
	}
	public int updatePerson(Person person){
		Condition condition=new Condition();
		condition.add("zPerno", person.getZPerno());
		return genericDao.updateByCondition(person, new String[]{"zPerna","zMobph","zUpdat","zDept","zSector","zCentre"}, condition);
	}
	public int updateDept(Dept dept){
		Condition condition=new Condition();
		condition.add("zDeptId", dept.getZDeptId());
		return genericDao.updateByCondition(dept, new String[]{"zDeptNm","zLevel","zUpdat","zParentId","zOrg"}, condition);
	}
	@SuppressWarnings("unchecked")
	public List<ReqStatRegno>  getReqStatByRegno(Map<String,String> map)
	{
		return  genericDao.queryBySqlID("domain.multiTable.getReqStatByRegno", map);
	}
	@SuppressWarnings("unchecked")
	public List<ReqStatRegno>  getReqStatByPerson(Map<String,String> map)
	{
		return  genericDao.queryBySqlID("domain.multiTable.getReqStatByPerson", map);
	}
	@SuppressWarnings("unchecked")
	public List<ReqStatRegno>  getReqStatByPersonAll(Map<String,String> map)
	{
		return  genericDao.queryBySqlID("domain.multiTable.getReqStatByPersonAll", map);
	}
	@SuppressWarnings("unchecked")
	public List<ReqStatSys>  getReqStatBySys(Map<String,String> map)
	{
		return  genericDao.queryBySqlID("domain.multiTable.getReqStatBySys", map);
	}
	public List<UnsubList>  getMsgUnsubList(Map<String,String> map,int pageNo,int pageSize )
	{
		//分页查询有错误,曹召启于20160509修改
		int firstRow = pageNo * pageSize;
		int lastRow = pageSize;
		
//		int firstRow = pageNo * pageSize + 1;
//		int lastRow = firstRow + pageSize - 1;
		map.put("firstRow", String.valueOf(firstRow));
		map.put("lastRow", String.valueOf(lastRow));
		return  genericDao.queryBySqlID("domain.multiTable.getUnsubList", map);
	}
	public List<MsgReqBean>  getMsgReqList(Map<String,String> map,int pageNo,int pageSize )
	{
		//分页查询有错误,曹召启于20160509修改
		int firstRow = pageNo * pageSize;
		int lastRow = pageSize;
		
//		int firstRow = pageNo * pageSize+1;
//		int lastRow = firstRow + pageSize - 1;
		
		map.put("firstRow", String.valueOf(firstRow));
		map.put("lastRow", String.valueOf(lastRow));
		return  genericDao.queryBySqlID("domain.multiTable.getMsgReqList", map);
	}
	public String getSeqId(String seq){
		String sqlString="select nextval('"+seq+"') as seq ";
		List lstList=genericDao.executeSql(sqlString);
		Map map=(Map)lstList.get(0);
		return String.valueOf(map.get("seq"));
	}
	
	//查询接口日志
	public List  listinterlogList(Map<String,String> map,int pageNo,int pageSize )
	{
		StringBuffer sb = new StringBuffer();
		
		int firstRow = pageNo * pageSize;
		int lastRow = firstRow + pageSize - 1;
		
		sb.append("SELECT a.ID,z_REQUEST_CONTENT,Z_RESPONSE_CONTENT,");
		sb.append(" case when b.z_sys_name is null then a.Z_SOURCE_SYS_ID ");
		sb.append(" else b.z_sys_name end Z_SOURCE_SYS_ID, ");
		sb.append(" case when c.z_sys_name is null  then a.Z_TARGET_SYS_ID ");
		sb.append(" else c.z_sys_name end Z_TARGET_SYS_ID, ");
		sb.append(" a.Z_TARGET_SERVICE,a.Z_STATE,a.Z_CRTIM,func_search_Log(id) as z_Msg");
		sb.append(" FROM  t_contentlog  a ");
		sb.append(" left join t_recv_system b  on b.z_sys_id = a.Z_SOURCE_SYS_ID");
		sb.append(" left join t_recv_system c  on c.z_sys_id = a.Z_TARGET_SYS_ID");
		sb.append(" where 1=1  ");
		if(map.get("zSourceSysId")!=null&&!map.get("zSourceSysId").equals("")){
			sb.append(" and a.Z_SOURCE_SYS_ID = '"+map.get("zSourceSysId")+"' ");//源系统
		}
		if(map.get("zTargetSysId")!=null&&!map.get("zTargetSysId").equals("")){
			sb.append(" and a.Z_TARGET_SYS_ID = '"+map.get("zTargetSysId")+"' ");//目标系统
		}
		if(map.get("zTargetService")!=null&&!map.get("zTargetService").equals("")){
			sb.append(" and a.Z_TARGET_SERVICE = '"+map.get("zTargetService")+"' ");//服务名称
		}
		if(map.get("zState")!=null&&!map.get("zState").equals("")){
			sb.append(" and a.Z_STATE = '"+map.get("zState")+"' ");//状态
		}
		if(map.get("beginDate")!=null&&!map.get("beginDate").equals("")){
			sb.append(" and a.Z_CRTIM >= '"+map.get("beginDate")+"' ");//开始时间
		}
		if(map.get("endDate")!=null&&!map.get("endDate").equals("")){
			sb.append(" and a.Z_CRTIM <= '"+map.get("endDate")+"' ");//结束时间
		}
		sb.append(" ORDER  BY  a.id desc LIMIT "+firstRow+","+pageSize+" ");
		System.out.println("查询接口日志==="+sb.toString());
		
		List lstList=genericDao.executeSql(sb.toString());
		return  lstList;
	}
	
	
	
	//查询轮播图片
	public List  listImgPlay(String fId)
	{
		StringBuffer sb = new StringBuffer();
		
		sb.append("SELECT  f_id,f_order,f_name,f_icon,f_url FROM t_carousel_pic   ");
		sb.append(" where 1=1 ");
		if(fId!=null&&!fId.equals("")){
			sb.append(" and  f_id = '"+fId+"' ");
		}
		sb.append(" ORDER  BY  f_order ");
		System.out.println("查询轮播图片==="+sb.toString());
		
		List lstList=genericDao.executeSql(sb.toString());
		return  lstList;
	}
	
	
	//保存修改轮播图片
	public int  saveImgPlay(HashMap map){
		StringBuffer sb = new StringBuffer();
		
        String f_id = String.valueOf(map.get("f_id"));
        System.out.println("图片主键===="+f_id);
        String f_name = String.valueOf(map.get("f_name"));//图片名称
        String f_icon = String.valueOf(map.get("f_icon"));//图片来源
        String f_url = String.valueOf(map.get("f_url"));//图片链接
        
		if(f_id!=null&&!f_id.equals("")){//修改数据
			sb.setLength(0);
			sb.append("update t_carousel_pic  set ");
			sb.append("f_name= '"+f_name+"',");
			sb.append("f_icon= '"+f_icon+"',");
			sb.append("f_url= '"+f_url+"' ");
			sb.append(" where ");
			sb.append(" f_id = '"+f_id+"' ");
			System.out.println("修改轮播图片==="+sb.toString());
		}

		int result = genericDao.updateBySqlStr(sb.toString());
		return  result;
	}
	
	//更新轮播图片
	public int  updateImgPlay(HashMap map){
		StringBuffer sb = new StringBuffer();
		
        String f_id = String.valueOf(map.get("f_id"));
        System.out.println("图片主键===="+f_id);
        String f_icon = String.valueOf(map.get("f_icon"));//图片名称
        
		if(f_id!=null&&!f_id.equals("")){//修改数据
			sb.setLength(0);
			sb.append("update t_carousel_pic  set ");
			sb.append("f_icon= '"+f_icon+"' ");
			sb.append(" where ");
			sb.append(" f_id = '"+f_id+"' ");
			System.out.println("修改轮播图片==="+sb.toString());
		}

		int result = genericDao.updateBySqlStr(sb.toString());
		return  result;
	}
	
	
	//查询接口日志数据条数
	public String  listinterlogListSize(Map map)
	{
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT count(ID) total FROM  t_contentlog  where 1=1  ");
		if(map.get("zSourceSysId")!=null&&!map.get("zSourceSysId").equals("")){
			sb.append(" and Z_SOURCE_SYS_ID = '"+map.get("zSourceSysId")+"' ");//源系统
		}
		if(map.get("zTargetSysId")!=null&&!map.get("zTargetSysId").equals("")){
			sb.append(" and Z_TARGET_SYS_ID = '"+map.get("zTargetSysId")+"' ");//目标系统
		}
		if(map.get("zTargetService")!=null&&!map.get("zTargetService").equals("")){
			sb.append(" and Z_TARGET_SERVICE = '"+map.get("zTargetService")+"' ");//服务名称
		}
		if(map.get("zState")!=null&&!map.get("zState").equals("")){
			sb.append(" and Z_STATE = '"+map.get("zState")+"' ");//状态
		}
		if(map.get("beginDate")!=null&&!map.get("beginDate").equals("")){
			sb.append(" and Z_CRTIM >= '"+map.get("beginDate")+"' ");//开始时间
		}
		if(map.get("endDate")!=null&&!map.get("endDate").equals("")){
			sb.append(" and Z_CRTIM <= '"+map.get("endDate")+"' ");//结束时间
		}
		System.out.println("查询接口日志条数==="+sb.toString());
		
		List lstList=genericDao.executeSql(sb.toString());
		
		String total = "0";
		if(lstList!=null&&lstList.size()>0){
			HashMap rh = (HashMap)lstList.get(0);
			total = String.valueOf(rh.get("total"));
		}
		return total;
	}
	
	//查询查询请求内容
	public List  requestDetail(String rowId )
	{
		
		String sql = "select Z_FILENAME,Z_SOURCE_SYS_ID,Z_TARGET_SYS_ID,Z_TARGET_SERVICE,Z_REQUEST_CONTENT,Z_RESPONSE_CONTENT,(select Z_URL from t_serviceconfig as aa where aa.Z_TARGET_SERVICE=a.Z_TARGET_SERVICE LIMIT 1) AS Z_URL from t_contentlog as a where id='"+rowId+"'";
		System.out.println("查询查询请求内容==="+sql);
		
		List lstList=genericDao.executeSql(sql);
		return  lstList;
	}
	public Long insertContengLog(Contentlog contentlog) {
		return genericDao.insert(contentlog);
	}
	//查询响应内容
	public List  responseDetail(String rowId ){
		
		String sql = "select Z_RESPONSE_CONTENT from t_contentlog where id='"+rowId+"'";
		System.out.println("查询查询响应内容==="+sql);
		
		List lstList=genericDao.executeSql(sql);
		return  lstList;
	}
	
	//查询源系统
	public List  sourceSys(){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT DISTINCT (a.Z_SOURCE_SYS_ID) Z_SOURCE_SYS_ID,");
		sb.append(" CASE WHEN b.Z_SYS_NAME IS NULL THEN ");
		sb.append(" a.Z_SOURCE_SYS_ID ");
		sb.append(" ELSE b.Z_SYS_NAME ");
		sb.append(" END  Z_SYS_NAME ");
		sb.append(" FROM t_contentlog a ");
		sb.append(" LEFT JOIN t_recv_system b ON a.Z_SOURCE_SYS_ID = b.z_sys_id ");
		sb.append(" ORDER BY a.Z_SOURCE_SYS_ID ");
//		String sql = "SELECT DISTINCT(Z_SOURCE_SYS_ID) Z_SOURCE_SYS_ID FROM  t_contentlog  ORDER  BY Z_SOURCE_SYS_ID";
		
		List lstList=genericDao.executeSql(sb.toString());
		return  lstList;
	}
	
	//查询目标系统
	public List  targetSys(){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT DISTINCT (a.Z_TARGET_SYS_ID) Z_TARGET_SYS_ID,");
		sb.append(" CASE WHEN b.Z_SYS_NAME IS NULL THEN ");
		sb.append(" a.Z_TARGET_SYS_ID ");
		sb.append(" ELSE b.Z_SYS_NAME ");
		sb.append(" END  Z_SYS_NAME ");
		sb.append(" FROM t_contentlog a ");
		sb.append(" LEFT JOIN t_recv_system b ON a.Z_TARGET_SYS_ID = b.z_sys_id ");
		sb.append(" ORDER BY a.Z_TARGET_SYS_ID ");
		
		
//		String sql = "SELECT DISTINCT(Z_TARGET_SYS_ID) Z_TARGET_SYS_ID FROM  t_contentlog  ORDER  BY Z_TARGET_SYS_ID";
		
		List lstList=genericDao.executeSql(sb.toString());
		return  lstList;
	}
	
	//查询服务名称
	public List  targetService(){
		String sql = "SELECT DISTINCT(Z_TARGET_SERVICE) Z_TARGET_SERVICE FROM  t_contentlog  ORDER  BY Z_TARGET_SERVICE";
		
		List lstList=genericDao.executeSql(sql);
		return  lstList;
	}
	
	//查询状态
	public List  getStatus(){
		String sql = "SELECT DISTINCT(func_search_Log(id))Z_STATE_NAME,Z_STATE  FROM  t_contentlog";
		
		List lstList=genericDao.executeSql(sql);
		return  lstList;
	}
	
	
	
	//查询接口日志
	public List  listcategory(){
		List result = new ArrayList();
		HashMap p = null;
		
		StringBuffer sb = new StringBuffer();
		//查询主表
		sb.append("SELECT  f_msg_category,f_msg_category_name,f_description,f_is_use  FROM  t_msg_category ORDER  BY f_msg_category");
		List list=genericDao.executeSql(sb.toString());
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				HashMap map = (HashMap)list.get(i);
				String f_msg_category = (String)map.get("f_msg_category");//种类主键
				String f_msg_category_name = (String)map.get("f_msg_category_name");//种类名称
				String f_description = (String)map.get("f_description");//种类描述
				String f_is_use = String.valueOf(map.get("f_is_use"));//种类是否使用
				System.out.println(f_msg_category_name+"种类是否使用====="+map.get("f_is_use"));
				p = new HashMap();
				p.put("id", f_msg_category);//主键
				p.put("categoryName", f_msg_category_name);//种类名称
				p.put("subCategoryName", " ");//类型名称
				p.put("isUse", f_is_use);//是否使用
				p.put("type", "1");//类型1:大类,0:小类
				result.add(p);
				
				
				//查询对应的子类
				sb.setLength(0);
				sb.append("SELECT  f_msg_sub_cat,f_msg_sub_cat_name,f_msg_description,f_is_use FROM t_msg_sub_cat where f_msg_category='"+f_msg_category+"'");
				List subList = genericDao.executeSql(sb.toString());
				if(subList!=null&&subList.size()>0){
					for(int j=0;j<subList.size();j++){
						HashMap subMap = (HashMap)subList.get(j);
						String f_msg_sub_cat = (String)subMap.get("f_msg_sub_cat");//子类主键
						String f_msg_sub_cat_name = (String)subMap.get("f_msg_sub_cat_name");//子类名称
						String f_msg_description = (String)subMap.get("f_msg_description");//子类描述
						String f_msg_is_use = String.valueOf(subMap.get("f_is_use"));//子类是否使用
						System.out.println(f_msg_sub_cat_name+"子类是否使用====="+subMap.get("f_is_use"));
						p = new HashMap();
						p.put("id", f_msg_sub_cat);//主键
						p.put("categoryName", " ");//种类名称
						p.put("subCategoryName", f_msg_sub_cat_name);//类型名称
						p.put("isUse", f_msg_is_use);//是否使用
						p.put("type", "0");//类型1:大类,0:小类
						result.add(p);
						
					}
				}
				
			}
		}		
		return  result;
	}
	
	
	/**
	 * 验证注册请求，成功后返回注册信息
	 * @param msgReq
	 * @return
	 */
	public MsgReg checkReqValid(MsgReq msgReq){
		MsgReg mReg=null;RecvPerson recvPerson=null;Person person=null;String invalidPersonStr="";boolean phoneChkret=false;
		if (!("1").equals(msgReq.getZMsgType())&&!("2").equals(msgReq.getZMsgType())){
			msgReq.setZMsgStatus("0");//无效请求
			msgReq.setZReqErr("无效的触发类型");
			return null;
		}
		if (StringUtils.isEmpty(msgReq.getZSrcSysId())||StringUtils.isEmpty(msgReq.getZRegId())||
			StringUtils.isEmpty(msgReq.getZMsgType())||StringUtils.isEmpty(msgReq.getZMsgContent())){
			msgReq.setZMsgStatus("0");//无效请求
			msgReq.setZReqErr("单据信息不完整");
			return null;
		}
		Condition condition=new Condition();
		condition.add("zSysId", msgReq.getZSrcSysId());
		List lst=genericDao.getByCondition(RecvSystem.class, condition, null);
		if (lst==null ||lst.size()!=1){
			msgReq.setZMsgStatus("0");//无效请求
			msgReq.setZReqErr("发送系统不存在");
			return null;
		}
		condition=new Condition();
		condition.add("zRegNo", msgReq.getZRegId());
		lst=genericDao.getByCondition(MsgReg.class,condition,null);
		if (lst==null ||lst.size()!=1){
			msgReq.setZMsgStatus("0");//无效请求
			msgReq.setZReqErr("未在短信平台注册");
			return null;
		}else {
			mReg=(MsgReg)lst.get(0);
			if (("Y").equals(mReg.getZIsapprv())){//审批类请求
				//审批类请求，必须有流程ID，单据Id，非终审和拒绝时必须有接收人
				if (StringUtils.isEmpty(msgReq.getZWfId())){
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("审批类请求流程ID必填");
					return null;
				}
				if (StringUtils.isEmpty(msgReq.getZCrtUsr())){
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("审批类请求提交用户必填");
					return null;
				}
				if (StringUtils.isEmpty(msgReq.getZFormId())){
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("审批类请求单据ID必填");
					return null;
				}
				if (StringUtils.isEmpty(msgReq.getZMsgReceiver())&&!("00").equals(msgReq.getZWfId())&&!("99").equals(msgReq.getZWfId())){
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("审批类请求无法找到接收人");
					return null;
				}
				boolean okExistY=false;
				if (("99").equals(msgReq.getZWfId())){//如果终审通过，通知注册时的接收人，所以需要验证
					//通知申请人，各流程没法都有接收人
					Condition condition2=new Condition();
					phoneChkret=false;
					condition2.add("zPerno", msgReq.getZCrtUsr());
					person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
					if (person!=null)//人员表不存在则认为手机号校验失败
						phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
					if (phoneChkret==false){//验证失败
						invalidPersonStr+=msgReq.getZCrtUsr()+",";
					}else{
						okExistY=true;
					}
//					condition=new Condition();
//					condition.add("zRegNo", msgReq.getZRegId());
//					lst=genericDao.getByCondition(RecvPerson.class, condition, null);
//					if (lst==null||lst.size()==0){
//						msgReq.setZMsgStatus("0");//无效请求
//						msgReq.setZReqErr("注册时未提供接收人员");
//						return null;
//					}
//					Condition condition2=new Condition();
//					phoneChkret=false;
//					for(int i=0;i<lst.size();i++){
//						condition2=new Condition();
//						recvPerson=(RecvPerson)lst.get(i);
//						condition2.add("zPerno", recvPerson.getZUsr());
//						person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
//						if (person!=null)
//							phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
//						if (phoneChkret==false){//验证失败
//							invalidPersonStr+=recvPerson.getZUsr()+",";
//						}else{
//							okExistY=true;
//						}
//						phoneChkret=false;
//					}
				}else if (("00").equals(msgReq.getZWfId())){//拒绝时，通知申请人
					Condition condition2=new Condition();
					phoneChkret=false;
					condition2.add("zPerno", msgReq.getZCrtUsr());
					person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
					if (person!=null)//人员表不存在则认为手机号校验失败
						phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
					if (phoneChkret==false){//验证失败
						invalidPersonStr+=msgReq.getZCrtUsr()+",";
					}else{
						okExistY=true;
					}
				}else{//审批中时，通知请求中的接收人
					String perArr[]=msgReq.getZMsgReceiver().split(",");
					Condition condition2=new Condition();
					phoneChkret=false;
					for (int k = 0; k < perArr.length; k++) {
						condition2=new Condition();
						condition2.add("zPerno", perArr[k]);
						person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
						if (person!=null)//人员表不存在则认为手机号校验失败
							phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
						if (phoneChkret==false){//验证失败
							invalidPersonStr+=perArr[k]+",";
						}else{
							okExistY=true;
						}
						phoneChkret=false;
					}
				}
				if (okExistY){
					if (!StringUtils.isEmpty(invalidPersonStr)){
						msgReq.setZReqErr("部分人员手机号为空或无效："+invalidPersonStr);
					}
				}else{
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("所有接收人员手机号为空或无效");
					return null;
				}
			}else if (("N").equals(mReg.getZIsapprv())){//非审批类，读取注册时的接收人员，然后验证其手机号
				condition=new Condition();
				condition.add("zRegNo", msgReq.getZRegId());
				lst=genericDao.getByCondition(RecvPerson.class, condition, null);
				//注册时没填写人员，发送时也没传入
				if ((lst==null||lst.size()==0)&&StringUtils.isEmpty(msgReq.getZMsgReceiver())){
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("未找到接收人员");
					return null;
				}
				Condition condition2=new Condition();boolean okExistY=false;
				phoneChkret=false;
				for(int i=0;i<lst.size();i++){
					condition2=new Condition();
					recvPerson=(RecvPerson)lst.get(i);
					condition2.add("zPerno", recvPerson.getZUsr());
					person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
					if (person!=null)
						phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
					if (phoneChkret==false){//验证失败
						invalidPersonStr+=recvPerson.getZUsr()+",";
					}else{
						okExistY=true;
					}
					phoneChkret=false;
				}
				String perArr[]=msgReq.getZMsgReceiver().split(",");
				phoneChkret=false;
				for (int k = 0; k < perArr.length; k++) {
					if (StringUtils.isEmpty(perArr[k])) continue;
					condition2=new Condition();
					condition2.add("zPerno", perArr[k]);
					person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
					if (person!=null)//人员表不存在则认为手机号校验失败
						phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
					if (phoneChkret==false){//验证失败
						invalidPersonStr+=perArr[k]+",";
					}else{
						okExistY=true;
					}
					phoneChkret=false;
				}
				if (okExistY){
					if (!StringUtils.isEmpty(invalidPersonStr)){
						msgReq.setZReqErr("部分人员手机号为空或无效："+invalidPersonStr);
					}
				}else{
					msgReq.setZMsgStatus("0");//无效请求
					msgReq.setZReqErr("所有接收人员手机号为空或无效");
					return null;
				}
			}
		}
		return mReg;
	}
	public MsgReq saveMsgRequest(MsgReq msgReq) throws Exception{
	
//		String seqId=getSeqId("s_req_id");自增长了
//		msgReq.setZReqId(new Long(seqId));
		msgReq.setCreateTimestamp(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		msgReq.setZMsgStatus("2");//默认未处理
		SimpleDateFormat dateformat1=new SimpleDateFormat("yyyyMMddHHmmss");
		String rtDate=dateformat1.format(msgReq.getCreateTimestamp());
		MsgReg mReg=checkReqValid(msgReq);
		genericDao.insert(msgReq);
		if (msgReq.getZMsgStatus().equals("2")){//如果请求有效，
			if (("2").equals(msgReq.getZMsgType())){//如果是立即执行的请求，生成请求任务
				doGenerateTask(msgReq,mReg);
			}
		}
		Condition condition=new Condition();
		condition.add("zRegNo",msgReq.getZRegId());
		MsgReg msgReg=(MsgReg)genericDao.getObjectByCondition(MsgReg.class, condition);
		if (msgReg!=null&&("Y").equals(msgReg.getZIsapprv())){
			//把单据ID对应的未处理请求置为无需处理
			String sql="update t_msg_req set z_msg_status = '1' where z_msg_status = '2' and z_form_id='"+msgReq.getZFormId()
			+"' and to_char(z_crt_time,'yyyymmddhh24miss')<to_char(now(),'yyyymmddhh24miss') and z_reg_id='"+msgReq.getZRegId()+"'";
			genericDao.executeSql(sql);
		}
		return msgReq;
	}
	public PermAuthnManager saveUser(PermAuthnManager permAuthnManager) throws Exception{
		
		String seqId=getSeqId("s_sys_id");
		permAuthnManager.setPk(new Long(seqId));
		String newPasswordDigest = passwordEncoder.encodePassword(permAuthnManager.getPassword(),null);
		permAuthnManager.setPassword(newPasswordDigest);
		genericDao.insert(permAuthnManager);
		return permAuthnManager;
	}
	public List getPerson(Person person){
		Condition condition=new Condition();
		condition.add("zPerno",person.getZPerno());
		return genericDao.getByCondition(Person.class, condition,null);
	}
	public List<VTask> getMsgTaskList(MsgTask msgTask){
		Condition condition=new Condition();
		condition.add("zReqId",msgTask.getZReqId());
		return genericDao.getByCondition(VTask.class, condition,null);
	}
	public List<MsgSendlog> getMsgTaskLogList(MsgSendlog msgSendlog){
		Condition condition=new Condition();
		condition.add("", "", "instr(z_task_ids,'"+msgSendlog.getZTaskIds()+"')>0", true);
		return genericDao.getByCondition(MsgSendlog.class, condition,null);
	}
	/**
	 * 
	 * @param sendTaskBean
	 * @param taskList
	 */
	public void doExecSendMsg(SendTaskBean sendTaskBean,ArrayList<SendTaskBean> taskList) {
		String seqId="";Timestamp timestamp=null;String ret="";MsgTask msgTask=null;MsgSendlog msgSendlog=new MsgSendlog();
		Condition condition=new Condition();
		if (StringUtils.isEmpty(sendTaskBean.getZMsgContent())){
			ret="false";
			log.error(sendTaskBean.toString());
			log.error(taskList.toString());
		}else{
			if (("Y").equals(sendTaskBean.getzIsapprv())&&("1").equals(sendTaskBean.getZMsgType())){//审批类、延时请求
				String sql="select * ";
				sql+="from ";
				sql+="(    ";
				sql+="  select a.*,row_number() over(order by z_send_time desc) p_rownum  from t_msg_task a ";
				sql+="left join t_msg_req b on a.z_req_id=b.z_req_id ";
				sql+="  left join t_msg_reg c on b.z_reg_id =c.z_reg_no";
				sql+="  where a.z_recv_usr='"+sendTaskBean.getZRecvUsr()+"' and c.z_isapprv='Y'  and a.z_status='1'";  
				sql+=")as a  where p_rownum=1 and now()>=z_send_time+'"+CommonFunc.delayString+"'";
				List list=genericDao.executeSql(sql);
				if (list!=null&&list.size()>0){//以前给此人发过审批类短信，且在15分钟之前发的
					ret=CommonFunc.sendSMS(sendTaskBean);//调用短信接口进行发送
				}else{
					sql="  select a.*,row_number() over(order by z_send_time desc) p_rownum  from t_msg_task a ";
					sql+="left join t_msg_req b on a.z_req_id=b.z_req_id ";
					sql+="  left join t_msg_reg c on b.z_reg_id =c.z_reg_no";
					sql+="  where a.z_recv_usr='"+sendTaskBean.getZRecvUsr()+"' and c.z_isapprv='Y'  and a.z_status='1'"; 
					list=genericDao.executeSql(sql);
					if (list==null||list.size()==0){//此人从来没有成功发送过审批类短信
						ret=CommonFunc.sendSMS(sendTaskBean);//调用短信接口进行发送
					}else{//15分钟之内刚收到过审批类短信，本次不发送
						ret="ignore";
					}
				}
			}else{
				ret=CommonFunc.sendSMS(sendTaskBean);//调用短信接口进行发送
			}
		}
		seqId=getSeqId("s_send_id");
//		msgSendlog.setZSendId(new Long(seqId));
//		msgSendlog.setZSegId("00");//号段ID暂时置00
//		msgSendlog.setZSendContent(sendTaskBean.getZMsgContent());
//		msgSendlog.setZSendResult(ret);
//		timestamp=new Timestamp(Calendar.getInstance().getTimeInMillis());
//		msgSendlog.setZSendTime(timestamp);
		genericDao.insert(msgSendlog);
		
		if (taskList!=null&&taskList.size()>0){
			SendTaskBean oTaskBean=null;
			for (int i = 0; i < taskList.size(); i++) {
				oTaskBean=taskList.get(i);
				condition=new Condition();
				condition.add("zTaskId",oTaskBean.getZTaskId());
				msgTask=new MsgTask();
				msgTask.setZSendTime(timestamp);
				if (ret.equalsIgnoreCase("ok")){
					msgTask.setZStatus("1");//成功
				}else if (ret.equalsIgnoreCase("false")){
					msgTask.setZStatus("2");//失败
				}else if (ret.equalsIgnoreCase("ignore")){
					msgTask.setZStatus("4");//距离上次发送待审提醒未超过20分钟，无需发送，
				}
//				msgTask.setZSendCnt(new Long(oTaskBean.getZSendCnt().intValue()+1));
//				if (StringUtils.isEmpty(oTaskBean.getzSendIds())){
//					msgTask.setZSendIds(String.valueOf(msgSendlog.getZSendId()));
//				}else{
//					msgTask.setZSendIds(oTaskBean.getzSendIds()+","+String.valueOf(msgSendlog.getZSendId()));
//				}
				genericDao.updateByCondition(msgTask,new String[]{"zSendIds","zSendTime","zStatus","zSendCnt"}, condition);
			}
		}
	}
	public List getMsgTaskList() {
		Condition condition=new Condition();String maxCnt="3";//最多尝试3次
		if (CommonFunc.maxCnt.equals("")){
			condition.add("zCfgId", "MAXCNT");
			SystemConfig sConfig=(SystemConfig)genericDao.getObjectByCondition(SystemConfig.class, condition);
			if (sConfig!=null){
				maxCnt=sConfig.getZCfgVal();
			}
			CommonFunc.maxCnt=maxCnt;
		}else{
			maxCnt=CommonFunc.maxCnt;
		}
		HashMap map=new HashMap();
		map.put("maxCnt", maxCnt);
		map.put("preferOrder", "1");
		List lstList=genericDao.queryBySqlID("domain.multiTable.getSendTask", map);
		return lstList;
	}
	/**
	 * 定时从任务表中取出满足条件的记录，执行发送
	 */
	public void doSendMsg() {
		Condition condition=new Condition();String maxCnt="3";//最多尝试3次
		if (CommonFunc.maxCnt.equals("")){
			condition.add("zCfgId", "MAXCNT");
			SystemConfig sConfig=(SystemConfig)genericDao.getObjectByCondition(SystemConfig.class, condition);
			if (sConfig!=null){
				maxCnt=sConfig.getZCfgVal();
			}
			CommonFunc.maxCnt=maxCnt;
		}else{
			maxCnt=CommonFunc.maxCnt;
		}
		HashMap map=new HashMap();
		map.put("maxCnt", maxCnt);
		List lstList=genericDao.queryBySqlID("domain.multiTable.getSendTask", map);
		if (lstList!=null&&lstList.size()>0){
			SendTaskBean sendTaskBean=null;String prevRecvUsr="";String sMsgContent="";SendTaskBean oTaskBean=null;
			ArrayList<SendTaskBean> apprvList=new ArrayList<SendTaskBean>();ArrayList<SendTaskBean> notApprvList=new ArrayList<SendTaskBean>();
			for (int i = 0; i < lstList.size(); i++) {
				sendTaskBean=(SendTaskBean)lstList.get(i);
				if(!prevRecvUsr.equals(sendTaskBean.getZRecvUsr())){
					if (apprvList.size()>0||notApprvList.size()>0){//开始组织内容调用发送
						if (apprvList.size()>0){
							if (apprvList.size()>1){
								sMsgContent="您目前有"+apprvList.size()+"条超过15分钟未处理的工作事项，请及时处理。";
							}else{
								sMsgContent=((SendTaskBean)apprvList.get(0)).getZMsgContent();
							}
							oTaskBean=((SendTaskBean)apprvList.get(0));
							oTaskBean.setZMsgContent(sMsgContent);
							doExecSendMsg(oTaskBean, apprvList);
						}
						if (notApprvList.size()>0){
							if (notApprvList.size()>1){
								SendTaskBean oNotApprvBean=null;sMsgContent="";
								for (int j = 0; j < notApprvList.size(); j++) {
									oNotApprvBean=notApprvList.get(j);
									sMsgContent+=oNotApprvBean.getZMsgContent()+"\n\r";
								}
							}else{
								sMsgContent=((SendTaskBean)notApprvList.get(0)).getZMsgContent();
							}
							oTaskBean=((SendTaskBean)notApprvList.get(0));
							oTaskBean.setZMsgContent(sMsgContent);
							doExecSendMsg(oTaskBean, notApprvList);
						}
					}
					apprvList=new ArrayList<SendTaskBean>();
					notApprvList=new ArrayList<SendTaskBean>();
				}
				prevRecvUsr=sendTaskBean.getZRecvUsr();
				if (("Y").equalsIgnoreCase(sendTaskBean.getzIsapprv())){
					if (!("99").equals(sendTaskBean.getZWfId())&&!("00").equals(sendTaskBean.getZWfId())){
						apprvList.add(sendTaskBean);
					}else{
						notApprvList.add(sendTaskBean);
					}
				}else if (("N").equalsIgnoreCase(sendTaskBean.getzIsapprv())){
					notApprvList.add(sendTaskBean);
				}
			}
			if (apprvList.size()>0){
				if (apprvList.size()>1){
					sMsgContent="您目前有"+apprvList.size()+"条超过15分钟未处理的工作事项，请及时处理。";
				}else{
					sMsgContent=((SendTaskBean)apprvList.get(0)).getZMsgContent();
				}
				oTaskBean=((SendTaskBean)apprvList.get(0));
				oTaskBean.setZMsgContent(sMsgContent);
				doExecSendMsg(oTaskBean, apprvList);
			}
			if (notApprvList.size()>0){
				if (notApprvList.size()>1){
					SendTaskBean oNotApprvBean=null;sMsgContent="";
					for (int j = 0; j < notApprvList.size(); j++) {
						oNotApprvBean=notApprvList.get(j);
						sMsgContent+=oNotApprvBean.getZMsgContent()+"\n\r";
					}
				}else{
					sMsgContent=((SendTaskBean)notApprvList.get(0)).getZMsgContent();
				}
				oTaskBean=((SendTaskBean)notApprvList.get(0));
				oTaskBean.setZMsgContent(sMsgContent);
				doExecSendMsg(oTaskBean, notApprvList);
			}
			if (lstList!=null && lstList.size()>0){
				log.info("本次共发送"+lstList.size()+"个任务");
			}
			//task表的触发器会根据一个请求所有的task状态更新请求的最新状态
		}else{
			//log.info("未查到需要执行的发送任务");
		}
	}
	/**
	 * 读取退订记录
	 * @param zRegNo
	 * @param zPerno
	 * @param zMobile
	 * @return
	 */
	public Unsubscribe getUnsubscribe(String zRegNo,String zPerno,String zMobile){
		Unsubscribe unsubscribe=null;
		Condition condSubs=new Condition();
		condSubs.add("zRegNo", zRegNo);
		condSubs.add("","(z_mobile='"+zMobile+"' or z_perno='"+zPerno+"')","",true);
		unsubscribe=(Unsubscribe)genericDao.getObjectByCondition(Unsubscribe.class, condSubs);
		return unsubscribe;
	}
	/**
	 * 根据发送请求产生发送任务
	 * @param msgReq
	 */
	public void doGenerateTask(MsgReq msgReq,MsgReg msgReg){
		MsgTask msgTask=null;Unsubscribe unsubscribe=null;Condition condSubs=new Condition();Condition condition=new Condition();
		boolean phoneChkret=false;RecvPerson recvPerson=null;Person person=null;
		if (("Y").equals(msgReg.getZIsapprv())){//如果是审批流
			if (("99").equals(msgReq.getZWfId())){//如果终审通过，给注册时的接收人发短信
				//改为给申请人发短信
				Condition condition2=new Condition();
				phoneChkret=false;
				condition2.add("zPerno", msgReq.getZCrtUsr());
				person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
				if (person!=null)//人员表不存在则认为手机号校验失败
					phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
				if (phoneChkret==false){//验证失败
				}else{
					msgTask=new MsgTask();
					unsubscribe=getUnsubscribe(msgReq.getZRegId(), person.getZPerno(), person.getZMobph());
//					msgTask.setZCrtTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
					msgTask.setZMobile(person.getZMobph());
					msgTask.setZRecvUsr(person.getZPerno());
					msgTask.setZReqId(msgReq.getZReqId());
//					msgTask.setZSendCnt(new Long(0));
					if (unsubscribe==null){
						msgTask.setZStatus("0");//未发送
					}else{
						msgTask.setZStatus("3");//已退订
					}
					genericDao.insert(msgTask);
				}
//				condition=new Condition();
//				condition.add("zRegNo", msgReq.getZRegId());
//				List lst=genericDao.getByCondition(RecvPerson.class, condition, null);
//				if (lst==null||lst.size()==0){
//				}else{
//					Condition condition2=new Condition();
//					phoneChkret=false;
//					for(int i=0;i<lst.size();i++){
//						recvPerson=(RecvPerson)lst.get(i);
//						condition2.add("zPerno", recvPerson.getZUsr());
//						person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
//						if (person!=null)
//							phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
//						if (phoneChkret==false){//手机验证失败,不进入队列
//						}else{
//							msgTask=new MsgTask();
//							unsubscribe=new Unsubscribe();
//							condSubs=new Condition();
//							condSubs.add("zRegNo", msgReq.getZRegId());
//							condSubs.add("zMobile", person.getZMobph());
//							unsubscribe=(Unsubscribe)genericDao.getObjectByCondition(Unsubscribe.class, condition2);
//							msgTask.setZCrtTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
//							msgTask.setZMobile(person.getZMobph());
//							msgTask.setZRecvUsr(person.getZPerno());
//							msgTask.setZReqId(msgReq.getZReqId());
//							msgTask.setZSendCnt(new Long(0));
//							if (unsubscribe==null){
//								msgTask.setZStatus("0");//未发送
//							}else{
//								msgTask.setZStatus("3");//已退订
//							}
//							genericDao.insert(msgTask);
//						}
//						phoneChkret=false;
//					}
//				}
			}else if (("00").equals(msgReq.getZWfId())){//拒绝时，通知申请人
				Condition condition2=new Condition();
				phoneChkret=false;
				condition2.add("zPerno", msgReq.getZCrtUsr());
				person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
				if (person!=null)//人员表不存在则认为手机号校验失败
					phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
				if (phoneChkret==false){//验证失败
				}else{
					msgTask=new MsgTask();
					unsubscribe=getUnsubscribe(msgReq.getZRegId(), person.getZPerno(), person.getZMobph());
//					msgTask.setZCrtTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
					msgTask.setZMobile(person.getZMobph());
					msgTask.setZRecvUsr(person.getZPerno());
					msgTask.setZReqId(msgReq.getZReqId());
//					msgTask.setZSendCnt(new Long(0));
					if (unsubscribe==null){
						msgTask.setZStatus("0");//未发送
					}else{
						msgTask.setZStatus("3");//已退订
					}
					genericDao.insert(msgTask);
				}
			}else{//审批中，给请求中的接收人发短信
				String perArr[]=msgReq.getZMsgReceiver().split(",");
				Condition condition2=new Condition();
				phoneChkret=false;
				for (int k = 0; k < perArr.length; k++) {
					condition2=new Condition();
					condition2.add("zPerno", perArr[k]);
					person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
					if (person!=null)//人员表不存在则认为手机号校验失败
						phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
					if (phoneChkret==false){//手机验证失败,不进入队列
					}else{
						msgTask=new MsgTask();
						unsubscribe=getUnsubscribe(msgReq.getZRegId(), person.getZPerno(), person.getZMobph());
//						msgTask.setZCrtTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
						msgTask.setZMobile(person.getZMobph());
						msgTask.setZRecvUsr(person.getZPerno());
						msgTask.setZReqId(msgReq.getZReqId());
//						msgTask.setZSendCnt(new Long(0));
						if (unsubscribe==null){
							msgTask.setZStatus("0");//未发送
						}else{
							msgTask.setZStatus("3");//已退订
						}
						genericDao.insert(msgTask);
					}
					phoneChkret=false;
				}
			}
		}else{//非审批流程的请求，通知注册时的接收人
			condition=new Condition();
			if (StringUtils.isEmpty(msgReq.getZRelatedSysId())){
				condition.add("zSysId", "All");
			}else{
				condition.add("","(Z_SYS_ID='All' or Z_SYS_ID='"+msgReq.getZRelatedSysId()+"')","",true);
			}
			condition.add("zRegNo", msgReq.getZRegId());
			List lst=genericDao.getByCondition(RecvPerson.class, condition, null);
			if (lst==null||lst.size()==0){
				lst=new ArrayList<RecvPerson>();
			}else{
				Condition condition2=new Condition();
				phoneChkret=false;
				for(int i=0;i<lst.size();i++){
					condition2=new Condition();
					recvPerson=(RecvPerson)lst.get(i);
					condition2.add("zPerno", recvPerson.getZUsr());
					person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
					if (person!=null)
						phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
					if (phoneChkret==false){//手机验证失败,不进入队列
					}else{
						msgTask=new MsgTask();
						unsubscribe=getUnsubscribe(msgReq.getZRegId(), person.getZPerno(), person.getZMobph());
//						msgTask.setZCrtTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
						msgTask.setZMobile(person.getZMobph());
						msgTask.setZRecvUsr(person.getZPerno());
						msgTask.setZReqId(msgReq.getZReqId());
//						msgTask.setZSendCnt(new Long(0));
						if (unsubscribe==null){
							msgTask.setZStatus("0");//未发送
						}else{
							msgTask.setZStatus("3");//已退订
						}
						genericDao.insert(msgTask);
					}
					phoneChkret=false;
				}
			}
			//非审批类的也通知传入的接收人
			String perArr[]=msgReq.getZMsgReceiver().split(",");
			Condition condition2=new Condition();
			phoneChkret=false;boolean isRepeatUsr=false;
			for (int k = 0; k < perArr.length; k++) {
				if (StringUtils.isEmpty(perArr[k])) continue;
				isRepeatUsr=false;
				for (int i = 0; i < lst.size(); i++) {
					recvPerson=(RecvPerson)lst.get(i);
					if (recvPerson.getZUsr().equals(perArr[k])){
						isRepeatUsr=true;
						break;
					}
				}
				if (isRepeatUsr) continue;//接收人员存在于注册时的接收人员，跳过
				condition2=new Condition();
				condition2.add("zPerno", perArr[k]);
				person=(Person)genericDao.getObjectByCondition(Person.class, condition2);
				if (person!=null)//人员表不存在则认为手机号校验失败
					phoneChkret=CommonFunc.isMobileValid(person.getZMobph());
				if (phoneChkret==false){//手机验证失败,不进入队列
				}else{
					msgTask=new MsgTask();
					unsubscribe=getUnsubscribe(msgReq.getZRegId(), person.getZPerno(), person.getZMobph());
//					msgTask.setZCrtTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
					msgTask.setZMobile(person.getZMobph());
					msgTask.setZRecvUsr(person.getZPerno());
					msgTask.setZReqId(msgReq.getZReqId());
//					msgTask.setZSendCnt(new Long(0));
					if (unsubscribe==null){
						msgTask.setZStatus("0");//未发送
					}else{
						msgTask.setZStatus("3");//已退订
					}
					genericDao.insert(msgTask);
				}
				phoneChkret=false;
			}
		}
		//对应的请求ID置为已入队列
		MsgReq mReq=new MsgReq();Condition condition2=new Condition();
		mReq.setZMsgStatus("3");
		condition2.add("zReqId", msgReq.getZReqId());
		condition2.add("zMsgStatus","2");
		int cnt=genericDao.updateByCondition(mReq,  new String[]{"zMsgStatus"}, condition2);
		if (cnt==0){//请求已被其它同单据的请求改为无需处理，此时删除掉已生成的任务
			genericDao.deleteBySqlStr("delete from t_msg_task where z_req_id='"+msgReq.getZReqId()+"'");
		}else{
		}
		//调用更新表，启动触发器，检查如果都是退订，请求置为无需处理
		if (msgTask!=null)
			genericDao.update(msgTask,new String[]{"zSendCnt"});
	}
	public String  getMsgUnsubListSize(Map map)
	{
		List<String> lstList=genericDao.queryBySqlID("domain.multiTable.getUnsubListCnt", map);
		return (String)lstList.get(0);
	}
	public String  getMsgReqListSize(Map map)
	{
		List<String> lstList=genericDao.queryBySqlID("domain.multiTable.getMsgReqListCnt", map);
		return (String)lstList.get(0);
	}
	public String  getMsgRegListSize(Map map)
	{
		List<String> lstList=genericDao.queryBySqlID("domain.multiTable.getMsgReqListCnt", map);
		return (String)lstList.get(0);
	}
	public String saveMsgUnsub(Unsubscribe unsubscribe,SubscribeLog subscribeLog){
		if (unsubscribe!=null)
			unsubscribe.setZCrusr(getCurrentUsername());
		subscribeLog.setZCrusr(getCurrentUsername());
		if (("0").equals(subscribeLog.getZType())){//退订
			String sql="delete from T_UNSUBSCRIBE where Z_REG_NO='"+unsubscribe.getZRegNo()+"' and Z_PERNO='"+unsubscribe.getZPerno()+"'";
			genericDao.executeSql(sql);
			genericDao.insert(unsubscribe);
//			List lstList=genericDao.getByCondition(Unsubscribe.class, null, null);
			genericDao.insert(subscribeLog);
		}else if  (("1").equals(subscribeLog.getZType())){//恢复订阅
			String sql="delete from T_UNSUBSCRIBE where Z_REG_NO='"+subscribeLog.getZRegNo()+"' and Z_PERNO='"+subscribeLog.getZPerno()+"'";
			genericDao.executeSql(sql);
			genericDao.insert(subscribeLog);
		}
		return "0";
	}
	public List<PermAuthnManager>  getUserList(PermAuthnManager permAuthnManager,int pageNo,int pageSize )
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("createTimestamp",OrderPart.DESC);
		return  genericDao.getPagedByCondition(PermAuthnManager.class, condition, orderPart, pageNo, pageSize);
	}
	public String  getUserListSize(PermAuthnManager permAuthnManager)
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("createTimestamp",OrderPart.DESC);
		return String.valueOf(genericDao.getCountByCondition(PermAuthnManager.class, condition));
	}
	public List<Person>  getPersonList(Person person,int pageNo,int pageSize )
	{
		Condition condition=new Condition();
		if (person.getZPerno()!=null&&person.getZPerno().trim()!="")
			condition.add("zPerno","like",person.getZPerno()+"%");
		if (person.getZPerna()!=null&&person.getZPerna().trim()!="")
			condition.add("zPerna","like","%"+person.getZPerna()+"%");
		OrderPart orderPart=new OrderPart();
		orderPart.add("zCrdat",OrderPart.DESC);
		return  genericDao.getPagedByCondition(Person.class, condition, orderPart, pageNo, pageSize);
	}
	public String  getPersonListSize(Person person)
	{
		Condition condition=new Condition();
		if (person.getZPerno()!=null&&person.getZPerno().trim()!="")
			condition.add("zPerno",person.getZPerno());
		if (person.getZPerna()!=null&&person.getZPerna().trim()!="")
			condition.add("zPerna",person.getZPerna());
		OrderPart orderPart=new OrderPart();
		orderPart.add("zCrdat",OrderPart.DESC);
		return String.valueOf(genericDao.getCountByCondition(Person.class, condition));
	}
	
	public Person getPersonDetail(Person person)throws Exception{
		Condition condition=new Condition();
		condition.add("zPerno", person.getZPerno());
		return (Person)genericDao.getObjectByCondition(Person.class, condition);
	}
	
	
	//保存人员修改内容
	public int savePersonDetail(Person person)throws Exception{
		StringBuffer sb = new StringBuffer();
		sb.append("update t_person  set ");
		sb.append(" z_perna = '"+person.getZPerna()+"',");//姓名
		sb.append("z_mobph  = '"+person.getZMobph()+"',");//手机号码
		sb.append("z_telph  = '"+person.getZTelph()+"',");//办公电话
		sb.append("z_type  = '"+person.getZType()+"',");//人员类型
		sb.append("z_isenable  = '"+person.getZIsenable()+"'  ");//是否接受推送
		sb.append(" where ");
		sb.append(" z_perno = '"+person.getZPerno()+"' ");
		int count = genericDao.deleteBySqlStr(sb.toString());
		System.out.println("修改人员信息======"+sb.toString());
		
		return count;
	}
	
	//保存类别
	public int savecategory(String id,String isUse,String type)throws Exception{
		StringBuffer sb = new StringBuffer();
		System.out.println("000000000000000------isUse="+isUse);
		int count = 0;
		if(type.equals("1")){//修改大类
			sb.setLength(0);
			sb.append("update t_msg_category  set ");
			sb.append(" f_is_use = '"+isUse+"'");//姓名
			sb.append(" where ");
			sb.append(" f_msg_category = '"+id+"' ");
		   count = genericDao.deleteBySqlStr(sb.toString());
			System.out.println(count+"修改大类别信息======"+sb.toString());	
			
			//修改子类
			sb.setLength(0);
			sb.append("update t_msg_sub_cat  set ");
			sb.append(" f_is_use = '"+isUse+"'");//姓名
			sb.append(" where ");
			sb.append(" f_msg_category = '"+id+"' ");
			count = genericDao.deleteBySqlStr(sb.toString());
			System.out.println(count+"修改小类别信息======"+sb.toString());
			
		}else{
			sb.setLength(0);
			sb.append("update t_msg_sub_cat  set ");
			sb.append(" f_is_use = '"+isUse+"'");//姓名
			sb.append(" where ");
			sb.append(" f_msg_sub_cat = '"+id+"' ");
			count = genericDao.deleteBySqlStr(sb.toString());
			System.out.println(count+"修改小类别信息======"+sb.toString());
		}

		
		return count;
	}
	
	
	public List<Channel>  getChannelList(Channel channel,int pageNo,int pageSize )
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("zChannId",OrderPart.ASC);
		return  genericDao.getPagedByCondition(Channel.class, condition, orderPart, pageNo, pageSize);
	}
	public String  getChannelListSize(Channel channel)
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("createTimestamp",OrderPart.ASC);
		return String.valueOf(genericDao.getCountByCondition(Channel.class, condition));
	}
	public List<ChannSeg>  getChannelSegList(ChannSeg channSeg,int pageNo,int pageSize )
	{
		Condition condition=new Condition();
		if (channSeg.getZChannId()!=null&&channSeg.getZChannId().longValue()!=0)
			condition.add("zChannId", channSeg.getZChannId());
		OrderPart orderPart=new OrderPart();
		orderPart.add("zChannId",OrderPart.ASC);
		orderPart.add("zSegMb",OrderPart.ASC);
		return  genericDao.getPagedByCondition(ChannSeg.class, condition, orderPart, pageNo, pageSize);
	}
	public String  getChannelSegListSize(ChannSeg channSeg)
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("zCrdat",OrderPart.DESC);
		return String.valueOf(genericDao.getCountByCondition(ChannSeg.class, condition));
	}
	public List  getMsgRegList(MsgReg msgReg,int pageNo,int pageSize )
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("zSysId",OrderPart.ASC);
		orderPart.add("zRegNo",OrderPart.ASC);
		if (!StringUtils.isEmpty(msgReg.getZSysId()))
			condition.add("zSysId", msgReg.getZSysId());
		if (!StringUtils.isEmpty(msgReg.getZCrusr()))
			condition.add("zCrusr", msgReg.getZCrusr());
		return  genericDao.getPagedByCondition(MsgReg.class, condition, orderPart, pageNo, pageSize);
	}
	public String  getMsgRegListSize(MsgReg msgReg)
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		orderPart.add("zSysId",OrderPart.ASC);
		orderPart.add("createTimestamp",OrderPart.DESC);
		if (!StringUtils.isEmpty(msgReg.getZSysId()))
			condition.add("zSysId", msgReg.getZSysId());
		if (!StringUtils.isEmpty(msgReg.getZCrusr()))
			condition.add("zCrusr", msgReg.getZCrusr());
		return String.valueOf(genericDao.getCountByCondition(MsgReg.class, condition));
	}
	public MsgReg getMsgReg(MsgReg msgReg)throws Exception{
		Condition condition=new Condition();
		condition.add("zRegNo", msgReg.getZRegNo());
		return (MsgReg)genericDao.getObjectByCondition(MsgReg.class, condition);
	}
	public Channel getChannel(Channel channel)throws Exception{
		Condition condition=new Condition();
		condition.add("zChannId", channel.getZChannId());
		return (Channel)genericDao.getObjectByCondition(Channel.class, condition);
	}
	public ChannSeg getChannSeg(ChannSeg channSeg)throws Exception{
		Condition condition=new Condition();
		condition.add("zSegId", channSeg.getZSegId());
		return (ChannSeg)genericDao.getObjectByCondition(ChannSeg.class, condition);
	}
	public int removeMsgReg(MsgReg msgReg)throws Exception{
		int rt=0;
		if (msgReg!=null){
			Condition condition=new Condition();
			condition.add("zRegId", msgReg.getZRegNo());
			List lstList=genericDao.getByCondition(MsgReq.class, condition, null);
			if (lstList==null||lstList.size()==0){
				rt=genericDao.deleteBySqlStr("delete from t_msg_reg where z_reg_no='"+msgReg.getZRegNo()+"'");
				genericDao.deleteBySqlStr("delete from t_recv_person where z_reg_no='"+msgReg.getZRegNo()+"'");
			}
		}
		return rt;
	}
	public int removeChannl(Channel channel)throws Exception{
		int rt=0;
		if (channel!=null){
			genericDao.deleteBySqlStr("delete from t_chann_seg where z_chann_id='"+channel.getZChannId()+"'");
			rt=genericDao.deleteBySqlStr("delete from t_channel where z_chann_id='"+channel.getZChannId()+"'");
		}
		return rt;
	}
	public int removeChannlSeg(ChannSeg channSeg)throws Exception{
		int rt=0;
		if (channSeg!=null){
			rt=genericDao.deleteBySqlStr("delete from t_chann_seg where z_seg_id='"+channSeg.getZSegId()+"'");
		}
		return rt;
	}
	public Long saveChannl(Channel channel)throws Exception {
		if (channel==null){
			channel=new Channel();
		}
		channel.setZCrusr(getCurrentUsername());		
		if (channel.getZChannId()==null||channel.getZChannId().intValue()==0){
			genericDao.insert(channel);
		}else{
			genericDao.update(channel, null);
		}
		return channel.getZChannId();
	}
	public Long saveChannlSeg(ChannSeg channSeg)throws Exception {
		if (channSeg==null){
			channSeg=new ChannSeg();
		}
		channSeg.setZCrusr(getCurrentUsername());	
		if (channSeg.getZSegId()==null||channSeg.getZSegId().intValue()==0){
			genericDao.insert(channSeg);
		}else{
			genericDao.update(channSeg, null);
		}
		return channSeg.getZSegId();
	}
	public String saveMsgReg(MsgReg msgReg,List recvList,String sqlRule)throws Exception{
		if (msgReg!=null){
			if (StringUtils.isEmpty(msgReg.getZRegNo())){
				Condition condition=new Condition();String sRegNo="";
				condition.add("zSysId", msgReg.getZSysId());
				OrderPart orders=new OrderPart();
				orders.add("zRegNo", OrderPart.DESC);
				List lst=genericDao.getByCondition(MsgReg.class, condition, orders);
				if (lst!=null&&lst.size()>0){
					MsgReg msgReg2=(MsgReg)lst.get(0);
					String sCnt=msgReg2.getZRegNo().substring(4);
					sCnt=sCnt.replaceAll("^0+(?!$)", "");
					Integer iCnt=new Integer(sCnt);
					sCnt=String.valueOf(iCnt.intValue()+1);
					for(int i=0;i<3-sCnt.length();i++){
						sRegNo+="0";
					}
					sRegNo+=sCnt;
				}else{
					sRegNo="001";
				}
				sRegNo=msgReg.getZSysId()+sRegNo;
				msgReg.setZRegNo(sRegNo);
				msgReg.setCreateTimestamp(new Timestamp(Calendar.getInstance().getTimeInMillis()));
				genericDao.insert(msgReg);
			}else{
				Condition condition=new Condition();
				condition.add("zRegNo", msgReg.getZRegNo());
				msgReg.setModifyTimestamp(new Timestamp(Calendar.getInstance().getTimeInMillis()));
				genericDao.updateExclusiveByCondition(msgReg, new String[]{"createTimestamp"}, condition);
			}
		}
		if (StringUtils.isEmpty(sqlRule)){
			genericDao.deleteBySqlStr("delete from t_recv_person where z_reg_no='"+msgReg.getZRegNo()+"'");
		}else{
			genericDao.deleteBySqlStr("delete from t_recv_person where z_reg_no='"+msgReg.getZRegNo()+"' and "+sqlRule);
		}
		if (recvList!=null&&recvList.size()>0){
			HashMap map=null;
			for(int i=0;i<recvList.size();i++){
				map=(HashMap)recvList.get(i);
				map.put("zRegNo", msgReg.getZRegNo());
				map.put("zUsr", map.get("zUsr").toString().trim());
				map.put("zUsrNm", map.get("zUsrNm").toString().trim());
				genericDao.insert(RecvPerson.class, map);
			}
		}
		return msgReg.getZRegNo();
	}
	public List  getRecvPersons(MsgReg msgReg)
	{
		Condition condition=new Condition();
		condition.add("zRegNo", msgReg.getZRegNo());
		return genericDao.getByCondition(RecvPerson.class,condition,null);
	}
	public List getSystems(RecvSystem system){
		Condition condition=new Condition();
//		condition.add("zSysId", msgReg.getZSysId());
		return genericDao.getByCondition(RecvSystem.class,condition,null);
	}
	public List getSubCategorys(MsgSubCat msgSubCat){
		Condition condition=new Condition();
//		condition.add("zSysId", msgReg.getZSysId());
		return genericDao.getByCondition(VMsgSubCateInUse.class,condition,null);
	}
	public void saveSystemConfig(SystemConfig systemConfig){
		genericDao.updateBySqlStr("update t_system_config set z_cfg_val='"+systemConfig.getZCfgVal()+"' where z_cfg_id='"+systemConfig.getZCfgId()+"'");
	}
	public List<SystemConfig>  getSystemConfigList(SystemConfig systemConfig,int pageNo,int pageSize)
	{
		Condition condition=new Condition();
		return genericDao.getByCondition(SystemConfig.class,condition,null);
	}
	public String  getSystemConfigListSize(SystemConfig systemConfig)
	{
		Condition condition=new Condition();
		OrderPart orderPart=new OrderPart();
		return String.valueOf(genericDao.getCountByCondition(SystemConfig.class, condition));
	}
}
